package com.example.peibei.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.dingtao.common.bean.Order;
import com.dingtao.common.bean.OrderDetail;
import com.dingtao.common.bean.PaiDanDetail;
import com.dingtao.common.bean.SubmitOrder;
import com.dingtao.common.bean.User;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDActivity;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.DateUtils;
import com.dingtao.common.util.GlideUtils;
import com.dingtao.common.util.SPUtils;
import com.dingtao.common.util.UIUtils;
import com.dingtao.common.util.recyclerview.SpacingItemDecoration;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.service.presenter.ApplyPaiDanPresenter;
import com.example.peibei.service.presenter.CateOrderPresenter;
import com.example.peibei.service.presenter.CollectPresenter;
import com.example.peibei.service.presenter.OrderDetailPresenter;
import com.example.peibei.service.presenter.PaidanDetailPresenter;
import com.example.peibei.ui.adapter.OrderLikeListAdapter;
import com.example.peibei.ui.adapter.PaidanDateAdapter;
import com.example.peibei.ui.adapter.PaidanTimeAdapter;
import com.example.peibei.ui.adapter.RadioButtonAdapter;
import com.linxiao.framework.dialog.BottomDialog;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class PaiDanDetailActivity extends WDActivity {
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_category)
    TextView tv_category;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.tv_content)
    TextView tv_content;
    @BindView(R.id.tv_price)
    TextView tv_price;
    @BindView(R.id.tv_liulan)
    TextView tv_liulan;
    @BindView(R.id.tv_shenqing)
    TextView tv_shenqing;
    @BindView(R.id.tv_order_time)
    TextView tv_order_time;
    @BindView(R.id.tv_date)
    TextView tv_date;
    @BindView(R.id.tv_address2)
    TextView tv_address2;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.iv_img_one)
    ImageView iv_img_one;
    @BindView(R.id.iv_img_two)
    ImageView iv_img_two;
    @BindView(R.id.iv_img_three)
    ImageView iv_img_three;
    @BindView(R.id.ll_imgs)
    LinearLayout ll_imgs;
    @BindView(R.id.bt_submit)
    TextView bt_submit;
    @BindView(R.id.rv_like)
    RecyclerView rv_like;
    @BindView(R.id.tv_like)
    TextView tv_like;

    private String paidanId;
    private SPUtils spUtils;
    private String token;
    private long userId;
    private String mid;
    private String cityName = "";
    private String cityCode = "";
    private int age = 0;
    private String auto = "";
    private String gender = "";
    private String price = "";
    private PaiDanDetail orderDetail;
    private List<PaiDanDetail.SelectorDTO> radiobuttons;
    private List<String> radiobuttonTimes;
    private PaidanDateAdapter paidanDateAdapter;
    private PaidanTimeAdapter paidanTimeAdapter;
    private String chooseWeek;
    private String chooseTime;
    private String id;
    private ApplyPaiDanPresenter applyPaiDanPresenter;
    private CateOrderPresenter homeOrderPresenter;
    private OrderLikeListAdapter orderLikeListAdapter;
    List<Order.RecordsDTO> orders;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_paidan_detail;
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        paidanId = bundle.getString("paidanId");
        String type = bundle.getString("type");
        iv_back.setOnClickListener(v -> finish());
        spUtils = new SPUtils(PaiDanDetailActivity.this, SpConstant.USER_TOKEN);
        token = spUtils.getString(SpConstant.USER_TOKEN);
        userId = spUtils.getLong(SpConstant.USER_MID);
        radiobuttons = new ArrayList<>();
        radiobuttonTimes = new ArrayList<>();
        PaidanDetailPresenter paidanDetailPresenter = new PaidanDetailPresenter(new OrderDetailCall());
        applyPaiDanPresenter = new ApplyPaiDanPresenter(new ApplyPaidanCall());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        if (TextUtils.isEmpty(token)) {
            paidanDetailPresenter.reqeust(paidanId, "");
        } else {
            paidanDetailPresenter.reqeust(paidanId, "Bearer " + token);
        }
        if (TextUtils.isEmpty(type)) {
            bt_submit.setVisibility(View.VISIBLE);
        } else {
            bt_submit.setVisibility(View.GONE);
        }

        rv_like.setLayoutManager(new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false));
        orders = new ArrayList<>();
        orderLikeListAdapter = new OrderLikeListAdapter(orders);
        rv_like.setAdapter(orderLikeListAdapter);
        homeOrderPresenter = new CateOrderPresenter(new OrderCall());
        orderLikeListAdapter.setOnItemClickListener((adapter, view, position) -> {
            Order.RecordsDTO order = (Order.RecordsDTO) adapter.getData().get(position);
            String publishOrderId = order.getPublishOrderId();
            Bundle bundle1 = new Bundle();
            bundle1.putString("publishOrderId", publishOrderId);
            intent(OrderDetailActivity.class, bundle1);
        });

    }

    @OnClick(R.id.bt_submit)
    public void submitOrder() {
        if (TextUtils.isEmpty(token)) {
            intent(LoginActivity.class);
            return;
        }
        applyPaiDanPresenter.reqeust("Bearer " + token,id
//                , chooseWeek,  chooseTime.substring(11, 16)
        );

//        Bundle bundle = new Bundle();
//        bundle.putString("publishOrderId", paidanId + "");
//        bundle.putString("mid", mid);
//        intent(SubmitOrderActivity.class, bundle);
//        finish();
//        showOrderDetail();

    }

    @OnClick(R.id.iv_head)
    public void toPersonInfo() {
        Bundle bundle = new Bundle();
        bundle.putString("mid", mid);
        intent(PersonInfoActivityTwo.class, bundle);
    }

//    @OnClick(R.id.ll_collect)
//    public void collect() {
//        collectPresenter.reqeust("Bearer " + token, publishOrderId + "", "1");
//    }
//
//    @OnClick(R.id.ll_collected)
//    public void cancelCollect() {
//        collectPresenter.reqeust("Bearer " + token, publishOrderId + "", "0");
//    }

    @OnClick(R.id.iv_jubao)
    public void jubao() {
        showDialog();
    }

    private void showOrderDetail() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_paidan_detail, null);
        BottomDialog bottomDialog = new BottomDialog(this);
        bottomDialog.setContentView(dialogView);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.show();
        Window window = bottomDialog.getWindow();
        if (window != null) {
//            window.setGravity(Gravity.BOTTOM);
            ////解决宽度问题
            window.setGravity(Gravity.BOTTOM);
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            window.setAttributes(params);
            window.setBackgroundDrawableResource(R.drawable.shape_white_bg);
        }
        ImageView iv_head = dialogView.findViewById(R.id.iv_head);
        TextView tv_name = dialogView.findViewById(R.id.tv_name);
        TextView tv_address = dialogView.findViewById(R.id.tv_address);
        TextView tv_price = dialogView.findViewById(R.id.tv_price);
        TextView tv_cate = dialogView.findViewById(R.id.tv_cate);
        TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
        RecyclerView rv_date = dialogView.findViewById(R.id.rv_date);
        RecyclerView rv_time = dialogView.findViewById(R.id.rv_time);
        TextView bt_submit_apply = dialogView.findViewById(R.id.bt_submit_apply);
        Glide.with(PaiDanDetailActivity.this).load(orderDetail.getMemberImg()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv_head);
        tv_name.setText(orderDetail.getNickname());
        tv_address.setText(orderDetail.getArea());
        tv_price.setText(orderDetail.getPrice());
        tv_cate.setText(orderDetail.getCategory());
        rv_date.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        rv_date.addItemDecoration(new SpacingItemDecoration(30));
        paidanDateAdapter = new PaidanDateAdapter(radiobuttons, PaiDanDetailActivity.this);
        rv_date.setAdapter(paidanDateAdapter);
        radiobuttons.clear();
        radiobuttons.addAll(orderDetail.getSelector());
        paidanDateAdapter.notifyDataSetChanged();
        rv_time.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        rv_time.addItemDecoration(new SpacingItemDecoration(30));
        paidanTimeAdapter = new PaidanTimeAdapter(radiobuttonTimes, this);
        rv_time.setAdapter(paidanTimeAdapter);
//        for (int i = 0; i < radiobuttons.size(); i++) {
//            PaiDanDetail.SelectorDTO selectorDTO = radiobuttons.get(i);
//            if (selectorDTO.getStatus() == 1) {
//                resetDate(selectorDTO);
//                return;
//            }
//        }
        paidanDateAdapter.setOnItemClickListener(new PaidanDateAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(PaiDanDetail.SelectorDTO data, int pos) {
                if (data.getStatus() == 1) {
                    resetDate(data);
                    chooseWeek = data.getWeek();
                }
            }
        });
        paidanTimeAdapter.setOnItemClickListener(new PaidanTimeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(String data, int pos) {
                chooseTime = data;
            }
        });
        bt_submit_apply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(chooseWeek)) {
                    UIUtils.showToastSafe("请选择开始时间");
                    return;
                }
                if (TextUtils.isEmpty(chooseTime)) {
                    UIUtils.showToastSafe("请选择具体时间");
                    return;
                }
                applyPaiDanPresenter.reqeust("Bearer " + token, chooseWeek, id, chooseTime.substring(11, 16));
            }
        });
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
            }
        });
    }

    private String startTime;
    private int max;//最大时间
    private Date startDate;
    private Date endDate;

    private void resetDate(PaiDanDetail.SelectorDTO data) {
        try {
            max = data.getMax();
            startTime = data.getRealDate();
            startDate = DateUtils.dateParseHour(startTime, "");
            endDate = DateUtils.dateAddHours(startDate, max);

            radiobuttonTimes.clear();
            ArrayList<String> list = new ArrayList<>();
            list.add(startTime);
            for (int i = 0; i < max - 1; i++) {
                Date date = DateUtils.dateAddHours(startDate, i + 1);
                list.add(DateUtils.dateFormat(date, "yyyy-MM-dd HH:mm:ss"));
            }
            radiobuttonTimes.addAll(list);
            paidanTimeAdapter.notifyDataSetChanged();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void showDialog() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_report, null);
        BottomDialog bottomDialog = new BottomDialog(this);
        bottomDialog.setContentView(dialogView);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.show();
        TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
        LinearLayout ll_copy = dialogView.findViewById(R.id.ll_copy);
        LinearLayout ll_jubao = dialogView.findViewById(R.id.ll_jubao);
        LinearLayout ll_lahei = dialogView.findViewById(R.id.ll_lahei);
        tv_cancel.setOnClickListener(v -> bottomDialog.dismiss());
        ll_copy.setVisibility(View.GONE);
        ll_lahei.setVisibility(View.GONE);
        ll_jubao.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString("mid", mid);
            intent(ReportActivity.class, bundle);
            bottomDialog.dismiss();
        });

    }
    class OrderCall implements DataCall<Order> {

        @Override
        public void success(Order data, Object... args) {
            if (data.getRecords() == null || data.getRecords().size() < 2) {
                rv_like.setVisibility(View.GONE);
                tv_like.setVisibility(View.GONE);
            } else {
                rv_like.setVisibility(View.VISIBLE);
                tv_like.setVisibility(View.VISIBLE);
            }
            //添加列表并刷新
            if (homeOrderPresenter.getPage() == 1) {
                orders.clear();
            }
            orderLikeListAdapter.setNewInstance(data.getRecords());
            orderLikeListAdapter.notifyDataSetChanged();
        }

        @Override
        public void fail(ApiException e, Object... args) {

        }
    }

    class OrderDetailCall implements DataCall<PaiDanDetail> {

        @Override
        public void success(PaiDanDetail data, Object... args) {
            setOrderDetail(data);
            orderDetail = getOrderDetail(data);

            homeOrderPresenter.reqeust(true, data.getCategoryId(), "", age, auto, cityCode, cityName, gender, price);
        }

        @Override
        public void fail(ApiException e, Object... args) {
            if (e.getCode().equals("8000")) {
                UIUtils.showToastSafe("登录过期，请重新登录");
                intent(LoginActivity.class);
                finish();
            }
        }
    }

    class ApplyPaidanCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
//            Bundle bundle = new Bundle();
//            bundle.putString("id", id);
//            intent(PaiDanOrderDetailActivity.class, bundle);
//            finish();
            User loginUser = SpConstant.getLoginUser();
            loginUser.setExistsApplyOrder(true);
            loginUser.setShowDispatchOrder(true);
            SpConstant.login(loginUser);
            Bundle bundle = new Bundle();
            bundle.putInt("index",2);
            bundle.putInt("type",1);
            intent(OrderWaitActivity.class,bundle);
        }

        @Override
        public void fail(ApiException e, Object... args) {
            if (e.getCode().equals("8000")) {
                UIUtils.showToastSafe("登录过期，请重新登录");
                intent(LoginActivity.class);
                finish();
            }else if(e.getCode().equals("500")){
                UIUtils.showToastSafe("您已申请接单,请勿重复申请~~");
            }
        }
    }

    private PaiDanDetail getOrderDetail(PaiDanDetail data) {
        return data;
    }

    private void setOrderDetail(PaiDanDetail data) {
        id = data.getId();
        mid = data.getMid();
        tv_date.setText(data.getBeginTime());
        tv_order_time.setText(data.getOrderTime());
        tv_address2.setText(data.getAddress());
        tv_name.setText(data.getNickname());
        tv_category.setText(data.getCategory());
        tv_address.setText("来自于"+data.getArea());
        tv_content.setText(data.getContent());
        tv_liulan.setText(data.getVisitCount() + "浏览");
        tv_shenqing.setText(data.getApplyCount() + "人已申请");
        if (data.getPrice().contains(".")) {
            String[] split = data.getPrice().split("\\.");
            tv_price.setText(split[0]);
        } else {
            tv_price.setText(data.getPrice());
        }
        if (data.getMid().equals(userId + "")) {
            bt_submit.setVisibility(View.GONE);
        } else {
            bt_submit.setVisibility(View.VISIBLE);
        }

        Glide.with(PaiDanDetailActivity.this).load(data.getMemberImg()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv_head);
        List<String> imgs = data.getImgs();
        if (imgs.size() > 0) {
            ll_imgs.setVisibility(View.VISIBLE);
            if (imgs.get(0) != null && !TextUtils.isEmpty(imgs.get(0))) {
                GlideUtils.loadImgTwo(PaiDanDetailActivity.this, imgs.get(0), 30, iv_img_one);
            }
            if (imgs.size() > 1) {
                if (imgs.get(1) != null && !TextUtils.isEmpty(imgs.get(1))) {
                    GlideUtils.loadImgTwo(PaiDanDetailActivity.this, imgs.get(1), 30, iv_img_two);
                }
            }
            if (imgs.size() > 2) {
                if (imgs.get(2) != null && !TextUtils.isEmpty(imgs.get(2))) {
                    GlideUtils.loadImgTwo(PaiDanDetailActivity.this, imgs.get(2), 30, iv_img_three);
                }
            }
        } else {
            ll_imgs.setVisibility(View.GONE);
        }
    }

    @Override
    protected void destoryData() {

    }
}
